package com.kfm.base.function2;

public class Demo05 {

    public static void main(String[] args) {
        /*
            递归： 方法自己调用自己, 要在方法体内存在结束调用的代码
         */
        int[] arr = {1, 2, 3, 4, 5};
        int key = 11;

        int index = binarySearch(arr, key);

        System.out.println(index);
    }

    public static int binarySearch(int[] arr, int key) {
        int left = 0;
        int right = arr.length - 1;

        int index = binarySearch(arr, key, left, right);

        return index;
    }

    public static int binarySearch(int[] arr, int key, int left, int right){
        if (left > right){
            return -1;
        }

        int middle = (left + right) / 2;
        if (arr[middle] == key){
            return middle;
        } else if (arr[middle] > key) {
            right = middle - 1;
        } else {
            left = middle + 1;
        }
        int index = binarySearch(arr, key, left, right);
        return index;
    }

}
